package cn.edu.zafu.bigdata.x.zcy_0217;

import java.io.*;
import java.net.*;

public class TimeClient {
    public static void main(String[] args) {
        String serverAddress = "127.0.0.1"; // 服务端IP地址
        int port = 1234; // 服务端端口号

        try (DatagramSocket socket = new DatagramSocket()) {
            System.out.println("Time client is running and sending request to the server...");

            byte[] sendData = new byte[1024];
            String message = "Time Request";
            sendData = message.getBytes();

            InetAddress serverInetAddress = InetAddress.getByName(serverAddress);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverInetAddress, port);
            socket.send(sendPacket);

            byte[] receiveBuffer = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
            socket.receive(receivePacket);
            long serverTime = Long.parseLong(new String(receivePacket.getData(), 0, receivePacket.getLength()));
            System.out.println("Received time from server: " + serverTime);

        } catch (UnknownHostException e) {
            System.err.println("Unknown host exception: " + e.getMessage());
            e.printStackTrace();
        } catch (SocketException e) {
            System.err.println("Socket exception: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
